//
//  LocationVC.m
//

#import "JzdxLocationVC.h"
#import <MapKit/MapKit.h>
#import <MapKit/MapKit.h>
#import <Contacts/Contacts.h>


@interface JzdxLocationVC ()<MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *viewMap;
@property (weak, nonatomic) MKMapView *mapView;
@property(nonatomic,assign)NSMutableArray *annotations;
@property (weak, nonatomic) IBOutlet UITextField *tfAddress;
@property (weak, nonatomic) IBOutlet UITextField *tfLat;
@property (weak, nonatomic) IBOutlet UITextField *tfLon;


@end

@implementation JzdxLocationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    MKMapView *mapView = [[MKMapView alloc] init];
    mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.viewMap addSubview:mapView];
    mapView.delegate = self;
    self.mapView = mapView;
    [mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_offset(0);
    }];
    self.annotations = [NSMutableArray array];
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(30.541991751726687, 104.05994953771059);
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(
        coordinate,
        1000,
        1000
    );
    [self.mapView setRegion:region animated:YES];
    [self addji:coordinate];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                              initWithTarget:self
                                              action:@selector(handleLongPress:)];
    longPress.minimumPressDuration = 0.5;
    [self.mapView addGestureRecognizer:longPress];
}

-(void)addji:(CLLocationCoordinate2D)touchCoordinate{
    [self trakerzreportlocation:touchCoordinate];
    [self.mapView removeAnnotations:self.mapView.annotations];
    MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
    annotation.coordinate = touchCoordinate;
    [self.mapView addAnnotation:annotation];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) return nil;
    static NSString *pinID = @"customPin";
    MKPinAnnotationView *pin = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinID];
    if (!pin) {
        pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinID];
        pin.pinTintColor = [UIColor redColor];
        pin.animatesDrop = YES;
    } else {
        pin.annotation = annotation;
    }
    return pin;
}


- (void)handleLongPress:(UIGestureRecognizer *)gesture {
    if (gesture.state != UIGestureRecognizerStateBegan) return;
    
    CGPoint touchPoint = [gesture locationInView:self.mapView];
    CLLocationCoordinate2D touchCoordinate = [self.mapView convertPoint:touchPoint
                                                  toCoordinateFromView:self.mapView];
    [self addji:touchCoordinate];
}

-(void)trakerzreportlocation:(CLLocationCoordinate2D )coordinate{

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude
                                                     longitude:coordinate.longitude];
    NSLog(@"===定位===> 经度: %f, 维度: %f",coordinate.longitude,coordinate.latitude);
    self.tfLon.text = [NSString stringWithFormat:@"%f",coordinate.longitude];
    self.tfLat.text = [NSString stringWithFormat:@"%f",coordinate.latitude];
    [geocoder cancelGeocode];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error) {
            NSLog(@"反地理编码错误: %@", error.localizedDescription);
            return;
        }
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks firstObject];
            NSString *addressString = [CNPostalAddressFormatter stringFromPostalAddress:placemark.postalAddress style:CNPostalAddressFormatterStyleMailingAddress];
            addressString = [addressString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            addressString = [addressString stringByReplacingOccurrencesOfString:@" " withString:@""];
            self.tfAddress.text = addressString;
        }
    }];
}



- (IBAction)onConfirm:(id)sender {
    NSString *lat = self.tfLat.text;
    NSString *lon = self.tfLon.text;
    NSString *address = self.tfAddress.text;
    if([self.delegate respondsToSelector:@selector(onLocation:lon:address:)]){
        [self.delegate onLocation:lat lon:lon address:address];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
